<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { toYuan, copyToCliboard, timeFormat_2 } from '@/hooks/util'
import * as integralProductApi from '@/api/integralProduct'
import { message } from 'ant-design-vue'
import Add from './components/Add.vue'
import EditStatus from './components/EditStatus.vue'

const route = useRoute()

const addRef = ref()
const editStatusRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '商品图片',
    key: 'img',
    width: 100,
  },
  {
    title: '积分/状态',
    key: 'price',
    width: 300,
  },
  {
    title: '标题/排序',
    key: 'title',
    width: 300,
  },
  {
    title: '商品标识/描述',
    key: 'extend',
    width: 400,
  },
  {
    title: '创建时间/库存',
    key: 'createTime',
    width: 400,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let {
      state,
      data,
      message: msg,
    } = await integralProductApi.getPointProductList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => getList())

import type { SelectProps } from 'ant-design-vue'
const typeList = ref<SelectProps['options']>([
  {
    label: '上架',
    value: 1,
  },
  {
    label: '下架',
    value: 2,
  },
])

const formRef = ref()
interface FormState {
  title?: string
  status?: number
  [propName: string]: any
}
const formState = reactive<FormState>({})

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.title = formState.title || ''
    if (formState.status) {
      searchParams.value.status = formState.status
    }
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }
  getList()
}

const add = () => {
  addRef.value.showModal('add')
}

const edit = (record: any) => {
  addRef.value.showModal('edit', record)
}

const del = async (id: string) => {
  try {
    let { state, message: msg } = await integralProductApi.deletePointProduct({ id })
    if (state === 200) {
      message.success('删除成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const editStatus = (record: any) => {
  // console.log('record=', record)
  editStatusRef.value.showModal(record)
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <div class="searchBox">
        <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
          <a-form-item label="标题" name="title">
            <a-input v-model:value="formState.title" placeholder="标题" />
          </a-form-item>

          <a-form-item label="状态" name="status">
            <a-select
              v-model:value="formState.status"
              placeholder="状态"
              style="width: 150px"
              allowClear
            >
              <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="search">搜索</a-button>
            <a-button @click="reset">重置</a-button>
            <a-button type="primary" @click="add">添加积分商品</a-button>
          </a-form-item>
        </a-form>
      </div>

      <a-table
        style="overflow-x: scroll"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="changePage"
        rowKey="id"
        size="small"
        :scroll="{ x: 100 }"
      >
        <template #emptyText>
          <a-empty description="暂无数据" />
        </template>

        <template #headerCell="{ column }">
          <template v-if="column.key === 'id'">
            <span>id</span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'img'">
            <a-popover placement="rightTop">
              <template #content>
                <div class="popoverImg">
                  <img :src="record.img" alt="" />
                </div>
              </template>
              <div class="imgBox">
                <img :src="record.img" alt="获取失败..." />
              </div>
            </a-popover>
          </template>

          <template v-else-if="column.key === 'title'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '90px' }">
              <a-descriptions-item label="标题">
                <a-tooltip placement="top">
                  <template #title>
                    <span>{{ record.title }}</span>
                  </template>
                  <div class="hiddenText">{{ record.title }}</div>
                </a-tooltip>
              </a-descriptions-item>
              <a-descriptions-item label="排序">
                {{ record.sort }}
              </a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-if="column.key === 'extend'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '110px' }">
              <a-descriptions-item label="商品标识">
                <a-tooltip placement="top">
                  <template #title>
                    <span>{{ record.extend }}</span>
                  </template>
                  <div class="hiddenText">{{ record.extend }}</div>
                </a-tooltip>
              </a-descriptions-item>
              <a-descriptions-item label="描述">
                <a-tooltip placement="top">
                  <template #title>
                    <span>{{ record.desc }}</span>
                  </template>
                  <div class="hiddenText">{{ record.desc }}</div>
                </a-tooltip>
              </a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-else-if="column.key === 'price'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
              <a-descriptions-item label="积分">
                {{ record.price }}
              </a-descriptions-item>
              <a-descriptions-item label="状态">
                <a-tag color="blue" v-if="record.status == 1" style="margin-right: 6px">上架</a-tag>
                <a-tag color="red" v-if="record.status == 2" style="margin-right: 6px">下架</a-tag>
                <EditOutlined @click="editStatus(record)" style="color: #1890ff" />
              </a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-else-if="column.key === 'createTime'">
            <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
              <a-descriptions-item label="创建时间">
                {{ timeFormat_2(record.createTime) }}
              </a-descriptions-item>
              <a-descriptions-item label="库存">
                {{ record.inventory }}
              </a-descriptions-item>
            </a-descriptions>
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-popconfirm
                placement="left"
                title="确认删除"
                ok-text="确认"
                @confirm="del(record.id)"
              >
                <a>删除</a>
              </a-popconfirm>

              <a @click="edit(record)">修改</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <Add ref="addRef" @refresh="getList"></Add>
    <EditStatus ref="editStatusRef" @refresh="getList"></EditStatus>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.aTag-seatNo:nth-child(n + 2) {
  margin-top: 3px;
}

.formClass {
  :nth-child(1) {
    margin-bottom: 2px;
  }
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  height: 50px;
  overflow: hidden;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 360px;

  img {
    width: 100%;
  }
}
</style>
